#ifndef _PEER_CONNECTION_H_
#define _PEER_CONNECTION_H_
#include <list>
#include "connection.h"
#include "module/config.h"
#include "lib/Socket.h"
#include "module/X7.h"
//管理对端连接的连接池
class peerConnection
{
private:
    int currentPeer = 0; //使用轮询法实现负载均衡

public:
    std::list<connection_t*> peers; //存储与对端服务器的连接<socketfd, connection_t*> 
    peerConnection()
    {
        for(int i = 0; i < numofPeers; i++)
        {
            int pos = peer_list[i].find(':');
            int len = peer_list[i].size();
            string _port = peer_list[i].substr(pos+1, len-pos-1);
            string addr = peer_list[i].substr(0, pos);
            int port = std::stoi(_port);
            if(startConnection(addr, port) == false)
            {
                string err = "对端服务器: "+addr+":"+ std::to_string(port) +" 连接失败";
                perror(err.c_str());
            }
        }  
        it = peers.begin();  
    }

    bool startConnection(string addr, int port)
    {
        int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if(sock < 0) 
            return false;
        struct sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
        serv_addr.sin_family = AF_INET;  //使用IPv4地址
        serv_addr.sin_addr.s_addr = inet_addr(addr.c_str());  //具体的IP地址
        serv_addr.sin_port = htons(port);  //端口
        if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) 
            return false;
        connection_t* temp = new connection_t();
        temp->setConnnection(sock, PEER_CONNECTION, nullptr, nullptr, false);
        temp->addr = serv_addr;
        temp->addrlen = sizeof(serv_addr);
        Socket::setNonblockingSocket(sock);
        peers.push_back(temp);
        return true;
    }


    void closeConnection(connection_t* conn)
    {
        if(conn == nullptr) return;
        close(conn->fd);
        peers.remove(conn);
        delete conn;
    }


    bool restartConnection(connection_t* conn){
        if(conn == nullptr) return true;
        if(connect(conn->fd, (struct sockaddr*)&conn->addr, conn->addrlen) < 0)
            return false;
        else 
            return true;
    }

    //使用轮转法实现负载均衡
    connection_t* getConnection()
    {
        if(peers.empty()) return nullptr;
        if(it == peers.end()) it = peers.begin();
        std::list<connection_t*>::iterator temp = it;
        it++;
        return *temp;

    }

    ~peerConnection() = default;

private:
    std::list<connection_t*>::iterator it; //用于指示将当前请求发送给哪个runner
};


#endif